# -*- coding: utf-8 -*-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# 文件：post_qdzj_company
# 日期：2019-12-02
# 备注：由于对有些渠道对同一客户10分钟内只能1次进件，为了性能测试的大并发量，必须每次进件传入的身份证都不相同
# 流程：1.get_idCard函数通过id获取指定数量的身份证（另外拿到了批量身份证存入到了数据库）存放到一个列表；
      2.将身份证号作为参数传入到不同渠道的进件json报文，组合后存入到列表中；
      3.创建多线程，将进件的json报文当成多线程参数传入到进件函数post()，这样能够确保线程启动非常快。
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import requests
from interfacetest.baseset.qdzjmsloan_api import API_QDZJ
from pycacho.cachobase.logger import Logger
from pycacho.cachobase.deal_company_code import create_organization
from pycacho.cachobase.deal_json import dict_to_json
from msydwork.md5_encrypt import md5_encrypt
from datetime import datetime

logger = Logger("post_qdzj_company").get_log()

qdzj_url = 'https://test.coo.msxiaodai.com/'

headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36'

        }

cur_time = datetime.now().strftime('%Y%m%d%H%M%S')
cur_day = datetime.now().strftime('%Y%m%d')

def get_sign(caseId,json_data,channel):
    if channel == 'IJFQ':
        secret_key = 'rsA8KESJkQ2A1E7xrT3SerLsx9v6RQJA8sfUjFeSjuJ88LPMLFq69DuxgNouTT7k'
    else:
        secret_key = 'jUeH4Jmc6mTVSPohiFvCCOkjertbNrMTv4tbdDkBEukO7bqr1CPFDAyXZu1tTl1D'
    keys = ['channelCd', 'channelType', 'productCd', 'serviceId', 'caseId']
    keys.sort()
    org_str = ''
    for i in range(len(keys)):
        if i == 0:
            org_str = org_str + keys[i] + '=' + caseId + '&'
        else:
            org_str = org_str + keys[i] + '=' + str(json_data['serviceHeader'][keys[i]]) + '&'
    return  md5_encrypt(org_str)

# 企业进件
def com_apply(channel,product,i):
    caseId = "AP" + channel + cur_time + '%04d'%(i)
    fu_url = qdzj_url + 'channel/apply'
    if channel == 'YGJ':
        json_data = API_QDZJ['comApply']
    elif channel == 'IJFQ':
        json_data = API_QDZJ['perApply']
    else:
        json_data = None
        print('暂不支持该渠道进件',channel)
        exit()
    json_data['serviceHeader']['channelCd'] = channel
    json_data['serviceHeader']['productCd'] = product
    json_data['serviceBody']['caseId'] = caseId
    json_data['serviceBody']['organCode'] = 'D8LGKN64-X'  # '21357513-2'  #create_organization()
    json_data['serviceHeader']['sign'] = get_sign(caseId,json_data,channel)
    dict_to_json(json_data)
    req1 = requests.post(fu_url,json=json_data,headers=headers)
    data = req1.text
    logger.info("企业进件接口响应信息：%s",data)

def com_contract(channel,product,i):
    caseId = "CT" + channel + cur_time + '%04d' % (i)
    fu_url = qdzj_url + 'channel/contract'
    if channel == 'IJFQ':
        json_data = API_QDZJ['com_iContract']
    else:
        json_data = API_QDZJ['com_yContract']
    json_data['serviceHeader']['channelCd'] = channel
    json_data['serviceHeader']['productCd'] = product
    json_data['serviceBody']['caseId'] = caseId
    json_data['serviceBody']['processNo'] = 'AMSEMP' + cur_day +'%06d'%(i)
    json_data['serviceHeader']['sign'] = get_sign(caseId,json_data,channel)
    dict_to_json(json_data)
    req1 = requests.post(fu_url,json=json_data,headers=headers)
    data = req1.text
    logger.info("借款协议签约接口响应信息：%s",data)

def com_transfer(channel,product,creditList,noticeList):
    caseId = "TF" + channel + cur_time
    fu_url = qdzj_url + 'channel/transfer'
    if channel == 'IJFQ':
        json_data = API_QDZJ['com_iTransfer']
    else:
        json_data = API_QDZJ['com_yTransfer']
    json_data['serviceHeader']['channelCd'] = channel
    json_data['serviceHeader']['productCd'] = product
    json_data['serviceBody']['caseId'] = caseId
    json_data['serviceBody']['fields']['creditList'] = creditList
    json_data['serviceBody']['fields']['noticeList'] = noticeList
    json_data['serviceHeader']['sign'] = get_sign(caseId,json_data,channel)
    dict_to_json(json_data)
    req1 = requests.post(fu_url,json=json_data,headers=headers)
    data = req1.text
    logger.info("债权转让协议签约接口响应信息：%s",data)

def batch_apply():
    for i in range(1,11):
        print('第' + str(i) +'笔进件：')
        com_apply(channel,product,i)

def batch_contract():
    for i in range(46,47):
        print('第' + str(i) +'笔合同签署：')
        com_contract(channel,product,i)

def batch_transfer():
    cur_day = datetime.now().strftime('%Y%m%d')
    creditList = []
    noticeList = []
    for i in range(5,6):
        if channel == 'IJFQ':
            credit_dict = {
                "processNo": 'AMSEMP' + cur_day + '%06d' % (i),
                "borrowContractNo": 'MS' + cur_day + '%06d' % (i),
                "borrowerName": "xxxx某某测试有限公司" + str(i),
                "contractStartDate": "2019-10-01",
                "contractEndDate": "2019-12-01",
                "borrowAmt": "1000.00",
                "borrowRate": str(i)
            }  # list必须放在循环内，要不然会覆盖，只是最新的数据
            notice_dict = {
                "processNo": 'AMSEMP' + cur_day + '%06d' % (i),
                "borrower": "xxxx某某测试有限公司" + str(i),
                "endYear": "2020",
                "endMonth": "04",
                "endDay": "01",
                "loanCapital": "1000.00",
                "guarantor":"测试",
                "transferYear":"2019",
                "transferMonth":"12",
                "transferDay":"05",
                "signYear":"2019",
                "signMonth":"12",
                "signDay":"06"
            }
        else:
            credit_dict = {
                "processNo": 'AMSEMP' + cur_day +'%06d'%(i),
                "borrowContractNo": 'MS' + cur_day +'%06d'%(i),
                "borrowerName": "xxxx某某测试有限公司" + str(i),
                "contractStartDate": "2019-10-01",
                "contractEndDate": "2019-12-01",
                "borrowAmt": "1000.00",
                "borrowRate": str(i),
                "transferTime": "2019-10-01"  # 债权转让时间
            }           # list必须放在循环内，要不然会覆盖，只是最新的数据
            notice_dict = {
                "processNo": 'AMSEMP' + cur_day +'%06d'%(i),
                "borrower": "xxxx某某测试有限公司" + str(i),
                "borrowContractNo": 'MS' + cur_day +'%06d'%(i),
                "accountName": "账号" + str(i),
                "accountNo": "6227" + str(i),
                "bankName": "中国农业银行"
            }
        creditList.append(credit_dict)
        noticeList.append(notice_dict)
    #print(creditList,noticeList)
    com_transfer(channel,product,creditList, noticeList)


if __name__ == '__main__':
    channel = 'IJFQ'           # YGJ-->企业    IJFQ-->个人
    product = 'IJFQ001'        # YGJ001+YGJ002   IJFQ001
    i = 4
    if i == 0:
        com_apply(channel,product,5)
    elif i == 1:
        com_contract(channel,product,5)
    elif i == 2:
        batch_apply()
    elif i == 3:
        batch_contract()
    elif i == 4:
        batch_transfer()

